package com.cskaoyan.util;

import com.cskaoyan.annotation.WdComponent;
import com.cskaoyan.annotation.WdScan;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author stone
 * @date 2022/11/10 20:52
 */
public class Container {

    Map map = new HashMap();

    Class configClass;

    Set<Class> classes;

    public Container(Class config) throws Exception {
        this.configClass = config;// 为了获得这个class上的注解中的value属性值
        init();
    }

    private void init() throws Exception {
        // 获得Configuration这个类上的@WdScan这个注解的value属性值 com.cskaoyan
        // 找到这个包下的所有的类 → 封装给set Set<Class> classes;
        getAllClassesInPackage(); // 你可以不看它具体的实例
        Iterator<Class> iterator = classes.iterator();
        while (iterator.hasNext()) {
            Class current = iterator.next();
            // 判断类上是否有@WdComponent注解
            if (current.isAnnotationPresent(WdComponent.class)) {
                // 获得类名
                String simpleName = current.getSimpleName();
                // 首字母小写
                char[] chars = simpleName.toCharArray();
                chars[0] += 32;
                simpleName = new String(chars);

                Object instance = current.newInstance();
                map.put(simpleName, instance);
            }
        }
    }

    private void getAllClassesInPackage() throws Exception {
        boolean annotationPresent = configClass.isAnnotationPresent(WdScan.class);
        if (!annotationPresent) {
            throw new Exception("without package");
        }
        WdScan declaredAnnotation = (WdScan) configClass.getDeclaredAnnotation(WdScan.class);
        String[] value = declaredAnnotation.value();
        classes = CommonUtil.getClasses(value[0]);
    }

    public Object getBean(String key) {
        return map.get(key);
    }
}
